<?php

namespace app\admin\controller;

use app\common\BaseHelper;
use app\common\Common;

use app\admin\model\Wxframeconf;
use app\admin\model\Wxcomponentconf;
use app\api\controller\HomeFrame;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 小程序首页配置
 */
class Customhome extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
    }

    public function index() {
        $request = Request::instance();
        $param = $request->param();
        
        $where = $this->defaultWhere;
        $confList = Wxframeconf::where($where)->order('sorting ASC, createDate ASC')->select();
        $homeFrame = new HomeFrame();
        foreach ($confList as $key => &$item) {
            switch ($item['typeId']) {
                case 1:
                    // 轮播图
                    break;
                case 2:
                    // 组合图
                    /*$combinationImg = json_decode($item['combinationImg'], true);
                    if($combinationImg){
                        $item['combinationImg'] = $combinationImg;
                    }*/
                    break;
                case 3:
                    // 推荐内容/列表
                    if($item['layoutContent']){
                        $item['layoutContentName'] = show_link_name($item['layoutContent']);
                        $item['linkType'] = $item['layoutContent'];

                        $item['contentList'] = $homeFrame->getCustomList($item, $where);
                    }
                    break;
                case 4:
                    // 视频
                    $field = 'imgUrl, videoUrl';
                    $component = Wxcomponentconf::where('frameId', $item['id'])->field($field)->find();
                    if($component){
                        $item['imgUrl'] = $component['imgUrl'];
                        $item['videoUrl'] = $component['videoUrl'];
                    }else{
                        $item['imgUrl'] = '';
                        $item['videoUrl'] = '';
                    }
                    break;
                case 6:
                    // 自适应图片
                    break;
                case 7:
                    // 按钮导航
                    break;
                default: break;
            }
        }

        // 小程序布局内容
        $this->assign('layoutContent', get_layout_content());
        // 组合图 链接
        $this->assign('links', get_link());
        $this->assign('confList', $confList);

        return $this->fetch('index');
    }

    /**
     * 根据frameId查询每个模块的具体内容
     */
    public function componentList() {
        $request = Request::instance();
        $param = $request->param();

        $model = new Wxcomponentconf();
        //$start = $param['start'];
        //$length = $param['length'];
        $order = 'sorting ASC';

        $where = [
            'frameId' => $param['frameId']
        ];
        $list = $model->where($where)->order($order)->select();
        $count = $model->where($where)->count();
        $result = [
            'status' => '1',
            //'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 保存模块数据
     */
    public function saveFrameconf() {
        $request = Request::instance();
        $param = $request->param();

        if(isset($param['combinationImg'])){
            $param['combinationImg'] = json_encode($param['combinationImg']);
        }
        if(isset($param['id']) && $param['id']) {
            $param['updateDate'] = time();
            $param['updateOper'] = $this->admin->id;
            $result = Wxframeconf::where('id', $param['id'])->update($param);
            if($result === false){
                return json(['code' => '2', 'message' => '出错，请重试']);
            }

            return json(['code' => '1', 'message' => '保存成功']);
        }

        $id = BaseHelper::getUUID();
        //$maxSort = Wxframeconf::where(['townId' => $this->admin->townId])->max('sorting');
        $data = [
            'id'=> $id,
            'page' => 'home',
            'createDate' => time(),
            'createOper' => $this->admin->id,
            'cityId' => $this->admin->cityId,
            'xianId' => $this->admin->xianId,
            'townId' => $this->admin->townId,
            //'sorting' => $maxSort + 1
            'sorting' => $param['sorting']
        ];
        $data = array_merge($param, $data);
        $result = Wxframeconf::insert($data);
        if($result !== false) {
            return json(['code' => '1', 'message' => '添加成功', 'id' => $id]);
        } else {
            return json(['code' => '2', 'message' => '添加失败']);
        }
    }

    /**
     * 删除模块
     */
    public function delFrameconf() {
        $request = Request::instance();
        $frameId = $request->param('frameId');

        Db::startTrans();
        try {
            $result = Wxframeconf::where('id', $frameId)->delete();
            if($result !== false){
                $res = Wxcomponentconf::where('frameId', $frameId)->delete();
                if($res !== false){
                    Db::commit();
                    return json(['code' => '1', 'message' => '删除成功']);
                }else{
                    Db::rollback();
                    return json(['code' => '2', 'message' => '删除失败']);
                }
            }else{
                Db::rollback();
                return json(['code' => '2', 'message' => '删除失败']);
            }
        } catch (Exception $e) {
            Db::rollback();
            return json(['code' => '3', 'message' => $e->getMessage()]);
        }
    }

    /**
     * 拖动排序
     */
    public function sort() {
        $request = Request::instance();
        $param = $request->param();
        foreach ($param as $item) {
            Wxframeconf::where('id', $item['id'])->update(['sorting' => $item['sorting']]);
        }

        return json(['code' => '1', 'message' => '排序成功']);
    }

    /**
     * 保存小程序组件内容
     */
    public function saveComponent() {
        $request = Request::instance();
        $param = $request->param();

        if(isset($param['id']) && $param['id']) {
            $param['updateDate'] = time();
            $param['updateOper'] = $this->admin->id;
            $result = Wxcomponentconf::where('id', $param['id'])->update($param);
            if($result === false){
                return json(['code' => '2', 'message' => '出错，请重试']);
            }

            return json(['code' => '1', 'message' => '保存成功']);
        }

        $id = BaseHelper::getUUID();
        $data = [
            'id' => $id,
            'page' => 'home',
            'createDate' => time(),
            'createOper' => $this->admin->id,
        ];
        $data = array_merge($param, $data);
        $result = Wxcomponentconf::insert($data);
        if($result !== false) {
            return json(['code' => '1', 'message' => '添加成功', 'id' => $id]);
        } else {
            return json(['code' => '2', 'message' => '添加失败']);
        }
    }

    /**
     * 删除小程序组件内容
     */
    public function delComponent() {
        $request = Request::instance();
        $id = $request->param('id');
        $result = Wxcomponentconf::where('id', $id)->delete();

        if($result !== false){
            return json(['code' => '1', 'message' => '删除成功']);
        }else{
            return json(['code' => '2', 'message' => '删除失败']);
        }
    }

    /**
     * 视频模块添加/编辑
     */
    public function saveVideo() {
        $request = Request::instance();
        $param = $request->param();

        $frame = $param['frame'];
        $component = $param['component'];
        Db::startTrans();
        try {
            $result = Wxframeconf::where('id', $frame['id'])->update($frame);
            if($result !== false){
                $componentInfo = Wxcomponentconf::where('frameId', $component['frameId'])->find();
                if($componentInfo) {
                    // 修改
                    $component['updateDate'] = time();
                    $component['updateOper'] = $this->admin->id;
                    $res = Wxcomponentconf::where('frameId', $component['frameId'])->update($component);
                } else {
                    // 新增
                    $data = [
                        'id' => BaseHelper::getUUID(),
                        'page' => 'home',
                        'createDate' => time(),
                        'createOper' => $this->admin->id,
                    ];
                    $data = array_merge($data, $component);
                    $res = Wxcomponentconf::insert($data);
                }

                if($res !== false){
                    Db::commit();
                    return json(['code' => '1', 'message' => '保存成功']);
                }else{
                    Db::rollback();
                    return json(['code' => '2', 'message' => '保存失败']);
                }
            }else{
                Db::rollback();
                return json(['code' => '2', 'message' => '更新模块失败']);
            }
        } catch (Exception $e) {
            Db::rollback();
            return json(['code' => '3', 'message' => $e->getMessage()]);
        }
    }

}